package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"yktwo/models/mysql"
	"yktwo/pkg"

	"yktwo/yktworpc/internal/svc"
	"yktwo/yktworpc/yktworpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改
func (l *UpdateLogic) Update(in *yktworpc.UpdateRequest) (*yktworpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("修改账号不存在")
	}

	update := mysql.User{
		Model:    gorm.Model{ID: uint(in.Id)},
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}

	if user.Password == pkg.Md5(in.NewPassword) {
		return nil, fmt.Errorf("新密码不可与原密码相同")
	}

	update.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Updates(&update)

	return &yktworpc.UpdateResponse{Id: int64(update.ID)}, nil
}
